<template>
    <div class="upload-alert f-l-c">
        <div class="u-a_title" v-if="type != 'create'">
            上传图片：<br>
            (提示：一次只能添加一张图片，添加第二张图片时会把原有的图片替换掉)
        </div>
        <el-upload v-model:file-list="bannerImage" :action="api" :headers="header" :data="submitData" list-type="picture-card" :limit="1" :on-exceed="handleExceed" :auto-upload="false" 
            ref="uploadRef" :multiple="false" @change="handleChange" :on-success="handleSuccess" :on-error="handleError">
            <el-icon>
                <Plus />
            </el-icon>
            <template #file="{ file }">
                <div>
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                </div>
            </template>
        </el-upload>
        <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, ref, toRefs } from 'vue'
import overallStore from '@/store/index'
import { Delete, Download, Files, Plus, ZoomIn } from '@element-plus/icons-vue'
import { ElMessage, genFileId } from 'element-plus'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import managePoemsListStore from '@/page/administrator/index/page/manage-poemsList/manage-poemsList.store'

const managePoemsListSe = managePoemsListStore()
const overallSe = overallStore()

// 获取请求API
let api = computed(() => {
    return window.sessionStorage.getItem('uploadApi')
})
const props = defineProps({
    type: {
        type: String,
        default: ''
    }
})
const { type } = toRefs(props)

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
// 请求头
const header = computed(() => {
    return {
        authorization: 'Bearer ' + overallSe.getToken
    }
})

const emits = defineEmits(['uploadBanner', 'getBannerInfo', 'clearInput', 'closeUploadAlert', 'alertTip'])

// 添加第二张图片时替换掉第一张图片
const uploadRef = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
    uploadRef.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    uploadRef.value!.handleStart(file)
}

// 添加文件时触发
const handleChange = (file: any) => {
    if(file.raw.type != 'image/jpeg' && file.raw.type != 'image/png' && file.raw.type != 'image/jpg' && file.raw.type != 'image/x-png') {
        setTimeout(() => {
            bannerImage.value = []
        }, 16)
        ElMessage({
            showClose: true,
            message: '仅限于上传png/jpg/jpeg格式的图片',
            type: 'error',
        })
        return
    } else {
        emits('getBannerInfo', file)
    }
}

// 上传图片成功
let isShowAlert = ref<string>('')
const handleSuccess = (res: any, file: any, files: any) => {
    uploadRef.value!.clearFiles()
    if(res.data.status = 'success') {
        emits('clearInput', true)
        if(type.value === 'change') {
            emits('alertTip', 'changeSuccess')
        } else {
            emits('alertTip', 'success')
        }
    }
}

// 上传图片失败
const handleError = (res: any, file: any, files: any) => {
    uploadRef.value!.clearFiles()
    emits('clearInput', false)
    emits('alertTip', 'failure')
}

// 点击添加图片按钮提交请求
let submitData = ref({})
let bannerImage = ref<any>([])
const handleDownload = (data: any) => {
    if(bannerImage.value.length == 0 && type.value != 'create') {
        if(type.value == 'change') {
            emits('alertTip', 'bannerImageEmpty')
        } else {
            ElMessage({
                showClose: true,
                message: '请选择上传的图片',
                type: 'error',
            })
        }
        return
    } 
    if(bannerImage.value.length == 0 && type.value == 'create') {
        managePoemsListSe.getCreatePoemsList(data).then((res: any) => {
            if(res.status == 'success') {
                emits('alertTip', 'success')
            } else {
                emits('alertTip', 'failure')
            }
            return 
        })
    }
    submitData.value = data
    uploadRef.value!.submit()
}  
defineExpose({
    handleDownload
})
</script>

<style lang="less" scoped>
.upload-alert {
    align-items: flex-start;
}
</style>